package com.interview.core.attachment.controller;

import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.interview.core.attachment.entity.Attachment;
import com.interview.core.attachment.service.AttachmentService;

@Controller
@RequestMapping(value = "attachment")
public class AttachmentController {
	@Resource
	private AttachmentService attachmentService;

	@RequestMapping(value = "index")
	public String indexLoad(ModelMap map) {
		return "load/loadIndex";
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	// {moduleName}
	public Object uploadFile(@RequestParam MultipartFile file, String moduleName) {

		Attachment attachment = attachmentService.saveFile(file, moduleName);

		return attachment;
	}

	@RequestMapping(value = "{id}/downLoad")
	public ResponseEntity<byte[]> downLoad(@PathVariable String id) throws IOException {

		Attachment attachment = attachmentService.findOne(id);
		 HttpHeaders headers = new HttpHeaders();  
		    headers.setContentType(MediaType.parseMediaType(attachment.getContentType())); 
		    headers.setContentDispositionFormData("attachment", attachment.getFileName());
		    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(attachmentService.processAbsolutePathForAttachment(attachment))),headers, HttpStatus.ACCEPTED); 
	}
	@RequestMapping(value="success")
	public String successPage(ModelMap map){
		return "load/succeed";
	}
	
	@RequestMapping
	@ResponseBody
	public Object attachmentfindAll() {
		return attachmentService.findAll();
	}
}
